import { ref, reactive, onMounted, h, createVNode } from "vue";
import { customerTaskApi } from "@/api/task";
import { getSalesList } from "@/api/crm";
import { uploadApi } from "@/api/upload";
import { message } from "@/utils/message";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessageBox, ElMessage, ElTag } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import { addDrawer } from "@/components/ReDrawer/index";
import { deviceDetection } from "@pureadmin/utils";
import { useRoute } from "vue-router";
import TaskCompleteForm from "../form.vue";
import TaskDetailView from "../detail.vue";
import customerDetailForm from "@/views/crm/customerDetail.vue";

export function useTaskList(tableRef) {
  const route = useRoute();

  const form = reactive({
    customer_name: "",
    follower_id: null as number | null,
    task_type: "",
    status: "", // 用于Tab切换的状态
    priority: null as number | null,
    urgent: "", // 即将超时筛选
    deadline_date: [],
    page: 1,
    limit: 15
  });

  const dataList = ref([]);
  const loading = ref(true);
  const selectedNum = ref(0);

  // 任务统计数据
  const statistics = ref({
    total: 0,
    pending: 0,
    completed: 0,
    overtime: 0
  });

  // 跟进人列表
  const followerList = ref([]);

  const pagination = reactive({
    total: 0,
    pageSize: 15,
    pageSizes: [10, 20, 40, 60, 100, 200],
    currentPage: 1,
    background: true
  });

  const columns = ref([
    { label: "勾选列", type: "selection", width: 50, fixed: true },
    {
      label: "任务ID",
      prop: "id",
      width: 80,
      align: "center",
      fixed: true
    },
    {
      label: "跟进人",
      prop: "follower.username",
      width: 90,
      showOverflowTooltip: true
    },
    {
      label: "优先级",
      prop: "priority",
      width: 80,
      align: "center",
      cellRenderer: ({ row }) => {
        const priorityMap = {
          1: { type: "info", text: "低" },
          2: { type: "warning", text: "中" },
          3: { type: "danger", text: "高" },
          4: { type: "danger", text: "紧急" }
        };
        const priority = priorityMap[row.priority] || { type: "info", text: "未知" };
        return h(ElTag, { type: priority.type, size: "small" }, {
          default: () => priority.text
        });
      }
    },
    {
      label: "客户姓名",
      prop: "customer.fullname",
      width: 120,
      showOverflowTooltip: true
    },
    {
      label: "客户邮箱",
      prop: "customer.email",
      width: 180,
      showOverflowTooltip: true
    },
    {
      label: "任务类型",
      prop: "task_type.name",
      width: 150,
      showOverflowTooltip: true
    },
    // {
    //   label: "任务内容",
    //   prop: "remark",
    //   minWidth: 200,
    //   showOverflowTooltip: true
    // },

    {
      label: "任务状态",
      prop: "status",
      width: 100,
      align: "center",
      cellRenderer: ({ row }) => {
        const statusMap = {
          0: { type: "info", text: "待处理" },
          1: { type: "success", text: "已完成" },
          2: { type: "danger", text: "超时完成" }
        };
        const status = statusMap[row.status] || { type: "info", text: "未知" };

        return h(ElTag, { type: status.type, size: "small" }, {
          default: () => status.text
        });
      }
    },
    {
      label: "反馈内容",
      prop: "feedback_text",
      width: 140,
      align: "center",
      cellRenderer: ({ row }) => {
        return row.feedback_text ? row.feedback_text : "-";
      }
    },
    {
      label: "截止时间",
      prop: "deadline_at",
      width: 140,
      align: "center",
      cellRenderer: ({ row }) => {
        if (!row.deadline_at) return "-";
        const deadline = new Date(row.deadline_at * 1000);
        const now = new Date();
        const isOverdue = deadline < now && row.status !== 1;

        return h("span", {
          style: { color: isOverdue ? "red" : "inherit" }
        }, deadline.toLocaleString());
      }
    },
    {
      label: "指派时间",
      prop: "created_at",
      width: 140,
      align: "center",
      cellRenderer: ({ row }) => {
        return row.created_at ? row.created_at : "-";
      }
    },
    {
      label: "完成时间",
      prop: "completed_at",
      width: 140,
      align: "center",
      cellRenderer: ({ row }) => {
        return row.completed_at ? new Date(row.completed_at * 1000).toLocaleString() : "-";
      }
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation" as const
    }
  ] as any);

  function resetForm(formEl?) {
    if (formEl) {
      formEl.resetFields();
    } else {
      // 重置时保留状态Tab选择
      const currentStatus = form.status;
      Object.assign(form, {
        customer_name: "",
        follower_id: null,
        task_type: "",
        status: currentStatus,
        priority: null,
        deadline_date: [],
        page: 1,
        limit: 15
      });
    }
    onSearch();
  }

  // 获取统计数据
  async function getStatistics() {
    try {
      // 构建统计查询参数，与列表查询保持一致的筛选条件
      const statsParams: Record<string, any> = {};

      // 如果有选中的跟进人员，添加到统计查询中
      if (form.follower_id) {
        statsParams.follower_id = form.follower_id;
      }

      // 也可以添加其他需要影响统计的筛选条件
      if (form.customer_name) {
        statsParams.customer_name = form.customer_name;
      }
      if (form.priority) {
        statsParams.priority = form.priority;
      }
      if (form.urgent) {
        statsParams.urgent = form.urgent;
      }

      const { data } = await customerTaskApi.statistics(statsParams);
      statistics.value = {
        total: data.total || 0,
        pending: data.pending || 0,
        completed: data.completed || 0,
        overtime: data.overtime || 0
      };
    } catch (error) {
      console.error("获取统计数据失败:", error);
    }
  }

  // 获取跟进人列表
  async function getFollowerList() {
    try {
      const { data } = await getSalesList({ page: 1, limit: 1000 });
      followerList.value = data.data || [];
    } catch (error) {
      console.error("获取跟进人列表失败:", error);
    }
  }

  async function onSearch() {
    loading.value = true;
    try {
      form.page = pagination.currentPage;
      form.limit = pagination.pageSize;

      // 构建请求参数，过滤掉无效值
      const searchParams = { ...form };

      // 过滤函数：移除null、undefined、空字符串等无效值
      const cleanParams = Object.keys(searchParams).reduce((acc, key) => {
        const value = searchParams[key];

        // 保留有效值：不为null、undefined、空字符串，数组要有内容
        if (value !== null &&
            value !== undefined &&
            value !== "" &&
            !(Array.isArray(value) && value.length === 0)) {
          acc[key] = value;
        }

        return acc;
      }, {});

      console.log('发送的查询参数:', cleanParams);

      const { data } = await customerTaskApi.list(cleanParams);
      dataList.value = data.data || [];
      pagination.total = data.total || 0;

      // 同时获取统计数据
      await getStatistics();
    } catch (error) {
      console.error("获取任务列表失败:", error);
      ElMessage.error("获取数据失败");
    } finally {
      loading.value = false;
    }
  }

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(selection) {
    selectedNum.value = selection.length;
  }

  function onSelectionCancel() {
    tableRef.value.getTableRef().clearSelection();
    selectedNum.value = 0;
  }



  async function handleComplete(row) {
    const formRef = ref();

    addDialog({
      title: "完成任务",
      props: {
        taskData: row
      },
      width: "500px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(TaskCompleteForm, {
        ref: formRef,
        taskData: row,
        viewCustomerDetail
      }),
      beforeSure: async (done, { options }) => {
        const formInstance = formRef.value?.getRef();
        const formData = formRef.value?.getFormData();

        if (!formInstance || !formData) {
          ElMessage.error("表单数据获取失败");
          return;
        }

        // 表单验证
        const isValid = await formInstance.validate().catch(() => false);
        if (!isValid) return;

        // 检查反馈要求
        const feedbackTypes = parseFeedbackType(row.task_type?.feedback_type);
        const needsText = feedbackTypes.includes("text");
        const needsImage = feedbackTypes.includes("image");

        if (needsText && !needsImage && !formData.feedback_text?.trim()) {
          ElMessage.error("请填写反馈内容");
          return;
        }

        if (needsImage && (!formData.feedback_images || formData.feedback_images.length === 0)) {
          ElMessage.error("请上传反馈图片");
          return;
        }

        try {
          const submitData: any = {
            feedback_text: formData.feedback_text || "",
            status: formData.status
          };

          // 如果有图片需要上传
          if (formData.feedback_images && formData.feedback_images.length > 0) {
            try {
              ElMessage.info(`正在上传 ${formData.feedback_images.length} 张图片...`);
              const uploadResults = [];

              // 逐个上传图片
              for (let i = 0; i < formData.feedback_images.length; i++) {
                const file = formData.feedback_images[i];
                try {
                  const uploadResult = await uploadApi.uploadImage(file);
                  if (uploadResult && uploadResult.id) {
                    uploadResults.push({
                      id: uploadResult.id,
                      path: uploadResult.path,
                      name: uploadResult.originalName
                    });
                  } else {
                    throw new Error(`第 ${i + 1} 张图片上传失败`);
                  }
                } catch (error) {
                  throw new Error(`第 ${i + 1} 张图片上传失败: ${error.message || error}`);
                }
              }

              // 所有图片上传成功
              submitData.feedback_attachments = uploadResults;
              ElMessage.success(`${uploadResults.length} 张图片上传成功`);

            } catch (uploadError) {
              console.error("图片上传失败:", uploadError);
              ElMessage.error(`图片上传失败: ${uploadError.message || uploadError}`);
              return;
            }
          }

          await customerTaskApi.complete(row.id, submitData);
          ElMessage.success("任务已完成");
          onSearch();
          done();
        } catch (error) {
          console.error("完成任务失败:", error);
          ElMessage.error("操作失败");
        }
      }
    });
  }

  // 解析反馈类型的辅助函数
  function parseFeedbackType(feedbackType: string | string[]): string[] {
    if (!feedbackType) return ["text"];

    // 如果已经是数组，直接返回
    if (Array.isArray(feedbackType)) {
      return feedbackType;
    }

    // 如果是字符串，尝试解析
    if (typeof feedbackType === "string") {
      try {
        // 尝试解析JSON格式
        const parsed = JSON.parse(feedbackType);
        return Array.isArray(parsed) ? parsed : [parsed];
      } catch {
        // 如果不是JSON，按逗号分割
        return feedbackType.split(",").map(t => t.trim());
      }
    }

    return ["text"];
  }

  function viewCustomerDetail(row) {
    if (!row.customer?.id) {
      ElMessage.warning("客户信息不完整");
      return;
    }

    // 使用Top数据模块的客户详情抽屉
    addDrawer({
      size: '60%',
      title: `客户详情:${row.customer.id}`,
      contentRenderer: () =>
        createVNode(customerDetailForm, {
          formInline: row.customer.id
        }),
    });
  }

  function viewTaskDetail(row) {
    if (row.status !== 1 && row.status !== 2) {
      ElMessage.warning("只能查看已完成任务的详情");
      return;
    }

    addDialog({
      title: "任务详情",
      props: {
        taskData: row
      },
      width: "600px",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(TaskDetailView, { taskData: row }),
      beforeSure: (done) => {
        done();
      }
    });
  }

  async function handleDelete(row) {
    try {
      await customerTaskApi.delete(row.id);
      ElMessage.success(`任务"${row.title}"删除成功`);
      onSearch();
    } catch (error) {
      console.error("删除任务失败:", error);
      const errorMessage = error?.response?.data?.message || error?.message || "删除失败";
      ElMessage.error(errorMessage);
    }
  }

  async function handleBatchDelete() {
    const selection = tableRef.value.getTableRef().getSelectionRows();
    if (selection.length === 0) {
      ElMessage.warning("请选择要删除的任务");
      return;
    }

    try {
      const ids = selection.map(item => item.id);
      await customerTaskApi.batchDestroy({ ids });
      ElMessage.success(`成功删除 ${selection.length} 个任务`);
      onSelectionCancel();
      onSearch();
    } catch (error) {
      console.error("批量删除任务失败:", error);
      const errorMessage = error?.response?.data?.message || error?.message || "批量删除失败";
      ElMessage.error(errorMessage);
    }
  }

  onMounted(() => {
    getFollowerList();
    getStatistics();
    handleUrlParams(); // 处理URL参数
    onSearch();
  });

  // 处理URL参数
  function handleUrlParams() {
    const query = route.query;

    // 处理各种参数
    if (query.status !== undefined) {
      form.status = Array.isArray(query.status) ? query.status[0] : query.status;
    }
    if (query.priority !== undefined) {
      const priorityValue = Array.isArray(query.priority) ? query.priority[0] : query.priority;
      const priorityNum = Number(priorityValue);
      if (!isNaN(priorityNum)) {
        form.priority = priorityNum; // 转换为数字类型
      }
    }
    if (query.urgent !== undefined) {
      form.urgent = Array.isArray(query.urgent) ? query.urgent[0] : query.urgent;
    }
    if (query.follower_id !== undefined) {
      const followerIdValue = Array.isArray(query.follower_id) ? query.follower_id[0] : query.follower_id;
      const followerIdNum = Number(followerIdValue);
      if (!isNaN(followerIdNum)) {
        form.follower_id = followerIdNum; // 转换为数字类型
      }
    }
    if (query.customer_name !== undefined) {
      form.customer_name = Array.isArray(query.customer_name) ? query.customer_name[0] : query.customer_name;
    }

    console.log('URL参数处理完成:', {
      status: form.status,
      priority: form.priority,
      follower_id: form.follower_id,
      urgent: form.urgent
    });
  }

  return {
    form,
    dataList,
    loading,
    columns,
    selectedNum,
    pagination,
    statistics,
    followerList,
    resetForm,
    onSearch,
    handleComplete,
    handleDelete,
    handleBatchDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onSelectionCancel,
    viewCustomerDetail,
    viewTaskDetail
  };
}
